import {Component, OnInit} from '@angular/core';
import {Router} from '@angular/router';
import {AddPlaceService} from './place.service';
import {BaseComponent} from '../common/base.component';
import {AddPlacePage, AddPlace} from './place';
import {AddEvent} from '../event/event';
import {FileUploader} from 'ng2-file-upload';
import {ParamConfig} from '../common/param.config';

declare var $: any;

@Component({
  selector: 'app-place',
  templateUrl: './place.component.html',
  styleUrls: ['./place.component.css']
})
export class PlaceComponent extends BaseComponent implements OnInit {
  uploader: FileUploader = new FileUploader({
    url: ParamConfig.HTTP_WEB_HOST_URL + 'rbFile/upload?type=3',
    method: 'POST',
    itemAlias: 'file',
    removeAfterUpload: true
  });
  eventIdTotal: any[];
  editorTitle: String = '';
  isAddEditor: boolean;
  curPage: Number = 1;
  fileId: string;
  addPlacePage: AddPlacePage;
  addPlace: AddPlace[];
  curaddPlace: AddPlace;
  addEvent: AddEvent[];
  eId: any[];
  strEvent: String = '';
  dd: any[];
  month: number;

  constructor(private addPlaceService: AddPlaceService, private router: Router) {
    super();
  }

  ngOnInit() {
    this.curaddPlace = {
      name: '',
      id: '',
      createTime: '',
      placeId: '',
      events: []
    };
    this.searchUser();
    // 初始化让下拉列表不显示
    $(function () {
      $('#selectBox').hide();
    });
    // 单击下拉列表时显示/隐藏下拉列表
    $('#box').click(function () {
      $('#selectBox').toggle();
    });
  }

  // 新增场景
  onAddPlace() {
    this.isAddEditor = true;
    this.editorTitle = '新增场景';
    this.curaddPlace = {
      name: '',
      id: '',
      createTime: '',
      placeId: '',
      events: []
    };
    this.queryListEventR();
    $('#data_editor').modal('show');
  }

// 修改
  onEditEvent(value: AddPlace) {
    this.isAddEditor = false;
    this.editorTitle = '修改场景';
    this.curaddPlace = value;
    $('#data_editor').modal('show');  // 显示编辑对话框
    this.queryPlaceEvent();
  }

// 删除
  onDeleteEvent(value: AddPlace) {
    this.curaddPlace = value;
    $('#delete_confirm').modal('show');  // 显示编辑对话框
  }

  // 图标
  selectedFileOnChanged(event: any) {
    console.log(event.target.value);
    // 这里是文件选择完成后的操作处理
    this.uploader.queue[0].onSuccess = (response, status, headers) => {
      // 上传文件成功
      if (status === 200) {
        // 上传文件后获取服务器返回的数据
        const tempRes = JSON.parse(response);
        this.fileId = tempRes.systemFileTO.fileId;
      } else {
        // 上传文件后获取服务器返回的数据错误
      }
    };
    this.uploader.queue[0].upload(); // 开始上传
  }

// 新增/修改
  save() {
    this.findItem();
    if (this.isAddEditor) { // 新增数据
      this.curPage = 1;
      this.addPlaceService.addPlaceinfo(this.curaddPlace, this.fileId, this.strEvent)
        .then(result => {
          if (result) {
            this.alert.info('新增成功');
            this.queryList();
          } else {
            this.alert.error('新增失败');
          }
        });
    } else { // 修改数据
      this.findItem();
      this.addPlaceService.updatePlaceinfo(this.strEvent, this.curaddPlace, this.fileId)
        .then(result => {
          if (result) {
            this.alert.info('修改成功');
            this.queryList();
          } else {
            this.alert.error('修改失败');
          }
        });
    }

    $('#data_editor').modal('hide');
  }

  // 删除
  delete() {
    this.addPlaceService.removeEventinfo(this.curaddPlace)
      .then(result => {
        if (result) {
          this.queryList();
          this.alert.info( '删除成功');
        } else {
          this.alert.error('删除失败');
        }
      });
    $('#delete_confirm').modal('hide');
  }

  // 查询用户
  searchUser() {
    this.curPage = 1;
    this.queryList();
  }

  onPage(event) {
    this.curPage = event;
    this.queryList();
  }

  queryList() {
    this.addPlaceService.getPlace(this.curPage)
      .then(page => {
          this.addPlacePage = page;
          this.addPlace = page.addPlace.datas;
        }
      );
  }

  // 新增查询事件ID
  queryListEventR() {
    this.addPlaceService.getEv(this.curPage)
      .then(page => {
          this.addEvent = page.addEvent.datas;
        }
      );
  }


// 编辑查询事件ID
  queryListEvent() {
    this.addPlaceService.getEv(this.curPage)
      .then(page => {
          this.addEvent = page.addEvent.datas;
          this.eventIdTotal = [];
          for (const index of this.addEvent) {
            this.eventIdTotal.push(index.id);
          }
          for (let i = 0; i < this.eventIdTotal.length; i++) {
            for (let j = 0; j < this.eId.length; j++) {
              if (this.eventIdTotal[i] === this.eId[j]) {
                for (const index of this.addEvent.filter(func => func.id === this.eventIdTotal[i])) {
                  Object.assign(index, {active: true});
                }
              }
            }
          }
        }
      );
  }

  queryPlaceEvent() {
    this.addPlaceService.getPlaceEvent(this.curaddPlace.id)
      .then(res => {
          if (res[0]) {
            this.queryListEvent();
            this.eId = res[1].eventIds;
          }
        }
      );
  }

  // 点击checkbox事件
  sureCheck(obj) {
    obj.active = !obj.active;
  }

// 点击按钮是弹出数组
  findItem() {
    let strR = '';
    for (const rgb of this.addEvent.filter(ele => ele.active === true)) {
      strR += rgb.id + ',';
      this.strEvent = strR.substr(0, strR.length - 1);
    }
  }
}
